package com.ruoyi.tb.lmt.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.util.ObjectUtil;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.helper.LoginHelper;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.ExcelUtils;
import com.ruoyi.common.utils.GuidUtil;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.domain.PageQuery;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.tb.lmt.domain.TbMaterial;
import com.ruoyi.tb.lmt.domain.bo.TbRepairplanBo;
import com.ruoyi.tb.lmt.domain.vo.*;
import com.ruoyi.tb.lmt.mapper.*;
import com.ruoyi.tb.lmt.service.ITbRepairplanService;
import lombok.RequiredArgsConstructor;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.xwpf.usermodel.*;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCol;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import com.ruoyi.tb.lmt.domain.bo.TbRepairplanlistBo;
import com.ruoyi.tb.lmt.domain.TbRepairplanlist;
import com.ruoyi.tb.lmt.service.ITbRepairplanlistService;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 计划明细Service业务层处理
 *
 * @author ruoyi
 * @date 2023-12-07
 */
@RequiredArgsConstructor
@Service
public class TbRepairplanlistServiceImpl implements ITbRepairplanlistService {

    private final TbRepairplanlistMapper baseMapper;

    @Autowired
    private TbRepairplanlistMapper tbRepairplanlistMapper;

    @Autowired
    private TbLmtrepairWorkdetailMapper tbLmtrepairWorkdetailMapper;

    @Autowired
    private TbLocomotiveMapper tbLocomotiveMapper;

    @Autowired
    private TbLmttypeMapper tbLmttypeMapper;

    @Autowired
    private TbSpecialInspectionMapper tbSpecialInspectionMapper;

    @Autowired
    private TbMutualInspectionMapper tbMutualInspectionMapper;

    @Autowired
    private TbAcceptanceMapper tbAcceptanceMapper;

    @Autowired
    private ITbRepairplanService iTbRepairplanService;

    @Autowired
    private TbRepairplanMapper tbRepairplanMapper;

    /**
     * 查询计划明细
     */
    @Override
    public TbRepairplanlistVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询计划明细列表
     */
    @Override
    public TableDataInfo<TbRepairplanlistVo> queryPageList(TbRepairplanlistBo bo, PageQuery pageQuery) {
        List<TbRepairplanlistVo> list = baseMapper.selectVoPageLeftJoinPlan(bo);
        if (ObjectUtil.isNotNull(pageQuery.getPageNum()) || ObjectUtil.isNotNull(pageQuery.getPageSize())) {
            List<TbRepairplanlistVo> page = ListUtil.page(pageQuery.getPageNum() - 1, pageQuery.getPageSize(), list);
            TableDataInfo res = new TableDataInfo<>(page, list.size());
            return res;
        } else {
            return TableDataInfo.build(list);
        }
    }

    /**
     * 查询计划明细列表
     */
    @Override
    public List<TbRepairplanlistVo> queryList(TbRepairplanlistBo bo) {
        LambdaQueryWrapper<TbRepairplanlist> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<TbRepairplanlist> buildQueryWrapper(TbRepairplanlistBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<TbRepairplanlist> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getLmtType()), TbRepairplanlist::getLmtType, bo.getLmtType());
        lqw.eq(StringUtils.isNotBlank(bo.getLmtNumber()), TbRepairplanlist::getLmtNumber, bo.getLmtNumber());
        lqw.eq(StringUtils.isNotBlank(bo.getRepairTimes()), TbRepairplanlist::getRepairTimes, bo.getRepairTimes());
        lqw.eq(StringUtils.isNotBlank(bo.getRepairChar()), TbRepairplanlist::getRepairChar, bo.getRepairChar());
        lqw.ge(bo.getRepairStartDate() != null, TbRepairplanlist::getRepairStartDate, bo.getRepairStartDate());
        lqw.le(bo.getRepairEndDate() != null, TbRepairplanlist::getRepairEndDate, bo.getRepairEndDate());
        lqw.eq(StringUtils.isNotBlank(bo.getStatus()), TbRepairplanlist::getStatus, bo.getStatus());
        lqw.eq(StringUtils.isNotBlank(bo.getWorkerTeam()), TbRepairplanlist::getWorkerTeam, bo.getWorkerTeam());
        return lqw;
    }

    /**
     * 新增计划明细
     */
    @Override
    public Boolean insertByBo(TbRepairplanlistBo bo) {
        TbRepairplanlist add = BeanUtil.toBean(bo, TbRepairplanlist.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改计划明细
     */
    @Override
    public Boolean updateByBo(TbRepairplanlistBo bo) {
        TbRepairplanlist update = BeanUtil.toBean(bo, TbRepairplanlist.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(TbRepairplanlist entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除计划明细
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public TableDataInfo<TbRepairplanlistVo> todoList(TbRepairplanlistBo bo, PageQuery pageQuery) {
        List<TbRepairplanlistVo> list = tbRepairplanlistMapper.todoList(bo);
        //分页
        if (ObjectUtil.isNotNull(pageQuery.getPageNum()) || ObjectUtil.isNotNull(pageQuery.getPageSize())) {
            List<TbRepairplanlistVo> page = ListUtil.page(pageQuery.getPageNum() - 1, pageQuery.getPageSize(), list);
            TableDataInfo res = new TableDataInfo<>(page, list.size());
            return res;
        } else {
            return TableDataInfo.build(list);
        }
    }

    @Override
    public List<TbRepairplanlistVo> selectStartList(String searchText, String planName, String workGroup) {
        List<TbRepairplanlistVo> list = tbRepairplanlistMapper.selectStartList(planName, workGroup);
        if (StringUtils.isNotBlank(searchText)) {
            list = list.stream().filter(item -> item.getLmtNumber().contains(searchText) || item.getLmtType().contains(searchText)).collect(Collectors.toList());
        }
        return list;

    }

    @Override
    public List<TbRepairplanlistVo> selectSecondList(String searchText, String planName, String workGroup) {
        List<TbRepairplanlistVo> list = tbRepairplanlistMapper.selectSecondList(planName, workGroup);
        if (StringUtils.isNotBlank(searchText)) {
            list = list.stream().filter(item -> item.getLmtNumber().contains(searchText) || item.getLmtType().contains(searchText)).collect(Collectors.toList());
        }
        return list;
    }


    @Override
    public List<TbRepairplanlistVo> selectOverhaulList(String searchText, String planName, String workGroup) {
        List<TbRepairplanlistVo> list = tbRepairplanlistMapper.selectOverhaulList(planName, workGroup);
        if (StringUtils.isNotBlank(searchText)) {
            list = list.stream().filter(item -> item.getLmtNumber().contains(searchText) || item.getLmtType().contains(searchText)).collect(Collectors.toList());
        }
        return list;
    }

    @Override
    public List<TbRepairplanlistVo> selectLegacyList(String searchText, String planName, String workGroup) {
        List<TbRepairplanlistVo> list = tbRepairplanlistMapper.selectLegacyList(planName, workGroup);
        if (StringUtils.isNotBlank(searchText)) {
            list = list.stream().filter(item -> item.getLmtNumber().contains(searchText) || item.getLmtType().contains(searchText)).collect(Collectors.toList());
        }
        return list;
    }


    @Override
    public List<TbRepairplanlistVo> selectCheckList(String searchText, String planName, String workGroup) {
        List<TbRepairplanlistVo> list = tbRepairplanlistMapper.selectCheckList(planName, workGroup);
        if (StringUtils.isNotBlank(searchText)) {
            list = list.stream().filter(item -> item.getLmtNumber().contains(searchText) || item.getLmtType().contains(searchText)).collect(Collectors.toList());
        }
        return list;
    }

    @Override
    public List<TbRepairplanlistVo> selectApprovalList(String searchText, String planName, String workGroup) {

        List<TbRepairplanlistVo> list = tbRepairplanlistMapper.selectApprovalList(planName, workGroup);
        if (StringUtils.isNotBlank(searchText)) {
            list = list.stream().filter(item -> item.getLmtNumber().contains(searchText) || item.getLmtType().contains(searchText)).collect(Collectors.toList());
        }
        return list;
    }

    @Override
    public TableDataInfo<TbRepairplanlistVo> selectLocomotiveList(String lmtType, String lmtNumber, String workerTeam, String planCode, String planName, String repairChar, String repairStartDate, String repairEndDate, PageQuery pageQuery) {

        List<TbRepairplanlistVo> result = tbRepairplanlistMapper.selectLocomotiveList(lmtType, lmtNumber, workerTeam, planCode, planName, repairChar, repairStartDate, repairEndDate);

        if (pageQuery.getPageSize() != null && pageQuery.getPageNum() != null) {
            List<TbRepairplanlistVo> page = ListUtil.page(pageQuery.getPageNum() - 1, pageQuery.getPageSize(), result);
            TableDataInfo res = new TableDataInfo<>(page, result.size());
            return res;
        } else {
            return TableDataInfo.build(result);
        }
    }

    @Override
    public Long selectPlanId(String lmtType, String lmtNumber) {
        return tbRepairplanlistMapper.selectPlanId(lmtType, lmtNumber);
    }

    @Override
    public List<TbRepairplanlistVo> selectMutualList(String searchText) {
        List<TbRepairplanlistVo> list = tbRepairplanlistMapper.selectMutualList();
        //对list里面的每一个子集合通过id查询出内容然后添加到各自的子集合中
        for (TbRepairplanlistVo item : list) {
            item.setTaskAllCount(tbLmtrepairWorkdetailMapper.selectTaskAllCount(item.getId()));
            item.setTaskFinishCount(tbLmtrepairWorkdetailMapper.selectFinishAllCount(item.getId()));
            item.setLegacyIssuesCount(tbLmtrepairWorkdetailMapper.selectLegacyIssuesCount(item.getId()));
        }
        if (StringUtils.isNotBlank(searchText)) {
            list = list.stream().filter(item -> item.getLmtNumber().contains(searchText) || item.getLmtType().contains(searchText)).collect(Collectors.toList());
        }
        return list;
    }

    @Override
    public List<TbRepairplanlistVo> selectSpecialList(String searchText) {
        List<TbRepairplanlistVo> list = tbRepairplanlistMapper.selectSpecialList();
        //对list里面的每一个子集合通过id查询出内容然后添加到各自的子集合中
        for (TbRepairplanlistVo item : list) {
            item.setTaskAllCount(tbLmtrepairWorkdetailMapper.selectTaskAllCount(item.getId()));
            item.setTaskFinishCount(tbLmtrepairWorkdetailMapper.selectFinishAllCount(item.getId()));
            item.setLegacyIssuesCount(tbLmtrepairWorkdetailMapper.selectLegacyIssuesCount(item.getId()));
            item.setWorkNeed(tbLmtrepairWorkdetailMapper.selectWorkNeed(item.getId()));
        }
        if (StringUtils.isNotBlank(searchText)) {
            list = list.stream().filter(item -> item.getLmtNumber().contains(searchText) || item.getLmtType().contains(searchText)).collect(Collectors.toList());
        }
        return list;
    }

    @Override
    public TbDigitalPlanListVo selectDigitalPlanList(String lmtType, String lmtNumber) {
        TbDigitalPlanListVo vo = new TbDigitalPlanListVo();
        vo.setLmtType(lmtType);
        vo.setLmtNumber(lmtNumber);
        vo.setLocomotiveStatus(tbLocomotiveMapper.selectStatusByLmtNumber(lmtNumber));
        Long lmtRepairId = tbRepairplanlistMapper.selectLmtId(lmtType, lmtNumber);
        vo.setLocomotiveStatus(tbLocomotiveMapper.selectStatusByLmtNumber(lmtNumber));
        if (lmtRepairId != null) {
            vo.setLmtRepairId(lmtRepairId);


            TbRepairplanlist planList = tbRepairplanlistMapper.selectById(lmtRepairId);
            if (planList.getWorkerTeam() != null) {
                vo.setWorkerTeam(planList.getWorkerTeam());
            }
            if (planList.getRepairChar() != null) {
                vo.setRepairChar(planList.getRepairChar());
            }
            if (planList.getRepairStartDate() != null) {
                vo.setRepairStartDate(planList.getRepairStartDate());
            }
            if (planList.getRepairEndDate() != null) {
                vo.setRepairEndDate(planList.getRepairEndDate());
            }
            Date startTime = planList.getRepairStartDate();
            if (startTime != null) {
                vo.setStartTime(startTime);
            }
            Date endTime = planList.getRepairEndDate();
            if (endTime != null) {
                vo.setEndTime(endTime);
            }
            if (planList.getRepairTimes() != null) {
                vo.setRepairTimes(planList.getRepairTimes());
            }
            if (planList.getRepairType() != null) {
                vo.setRepairType(planList.getRepairType());
            }
            if (planList.getExpirationDate() != null) {
                vo.setExpirationDate(planList.getExpirationDate());
            }

            //查询出计划的任务数
            vo.setTaskAllCount(tbLmtrepairWorkdetailMapper.selectTaskAllCount(lmtRepairId));
            vo.setTaskFinishCount(tbLmtrepairWorkdetailMapper.selectFinishAllCount(lmtRepairId));
            //根据lmtRepairId设置计划进度
            vo.setOverhaulProgress(planList.getStatus());
        }
        return vo;
    }

    @Override
    public List<TbRepairplanlistVo> selectAcceptanceList(String searchText) {
        List<TbRepairplanlistVo> list = tbRepairplanlistMapper.selectAcceptanceList();
        //对list里面的每一个子集合通过id查询出内容然后添加到各自的子集合中
        for (TbRepairplanlistVo item : list) {
            item.setTaskAllCount(tbLmtrepairWorkdetailMapper.selectTaskAllCount(item.getId()));
            item.setTaskFinishCount(tbLmtrepairWorkdetailMapper.selectFinishAllCount(item.getId()));
            item.setLegacyIssuesCount(tbLmtrepairWorkdetailMapper.selectLegacyIssuesCount(item.getId()));
            item.setWorkNeed(tbLmtrepairWorkdetailMapper.selectWorkNeed(item.getId()));
            item.setWorkNeed2(tbLmtrepairWorkdetailMapper.selectWorkNeed2(item.getId()));
        }
        if (StringUtils.isNotBlank(searchText)) {
            list = list.stream().filter(item -> item.getLmtNumber().contains(searchText) || item.getLmtType().contains(searchText)).collect(Collectors.toList());
        }
        return list;
    }

    @Override
    public TableDataInfo<TbRepairplanlistVo> selectHistoryDetailList(String lmtType, String lmtNumber, PageQuery pageQuery) {
        List<TbRepairplanlistVo> result = tbRepairplanlistMapper.selectHistoryDetailList(lmtType, lmtNumber);
        //分页
        if (pageQuery.getPageSize() != null && pageQuery.getPageNum() != null) {
            List<TbRepairplanlistVo> page = ListUtil.page(pageQuery.getPageNum() - 1, pageQuery.getPageSize(), result);
            TableDataInfo res = new TableDataInfo<>(page, result.size());
            return res;
        } else {
            return TableDataInfo.build(result);
        }
    }

    @Override
    public Boolean isTypeById(Long id) {
        return tbRepairplanlistMapper.isTypeById(id);
    }

    @Override
    public void export(HttpServletRequest request, HttpServletResponse response) {
        // 创建一个Excel工作簿
        Workbook workbook = new XSSFWorkbook();

        // 创建一个工作表sheet
        Sheet sheet = workbook.createSheet("检修计划");

        // 创建标题行
        Row titleRow = sheet.createRow(0);

        // 定义标题行的列名
        String[] columnHeaders = {
            "计划名称", "计划日期", "车型", "车号", "配属车间", "修别", "检修工队", "检修计划有效期", "计划开始日期", "计划结束日期", "状态", "是否更换捣固装置(0是1否)", "是否更换发动机(0是1否)", "备注"
        };

        // 设置单元格样式（可选）
        CellStyle headerStyle = workbook.createCellStyle();
        Font headerFont = workbook.createFont();
        headerFont.setBold(true);
        headerStyle.setFont(headerFont);

        // 创建标题行单元格并写入列名
        for (int i = 0; i < columnHeaders.length; i++) {
            Cell cell = titleRow.createCell(i);
            cell.setCellValue(columnHeaders[i]);
            cell.setCellStyle(headerStyle);
        }
        // 设置所有行高
        for (Row row : sheet) {
            row.setHeightInPoints(20);
        }

        // 设置所有列宽
        for (Sheet sh : workbook) {
            for (int i = 0; i < 300; i++) {
                sh.setColumnWidth(i, 14 * 256);
            }
        }

        OutputStream os = null;
        try {
            os = response.getOutputStream();
            workbook.write(os);
            os.flush();
            //os.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public Map<String, Object> updateExcel1(MultipartFile file) throws Exception {
        Map<String, Object> map = new HashMap<>();
        List<TbRepairplanBo> planList = new ArrayList<>();
        TbRepairplanBo bo = null;
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); // 用于日期解析

        try {
            Workbook workbook = new XSSFWorkbook(file.getInputStream());
            Sheet sheet = workbook.getSheetAt(0);
            DataFormatter formatter = new DataFormatter(); // 用于格式化Excel单元格的数据

            for (int rowIndex = 1; rowIndex <= sheet.getLastRowNum(); rowIndex++) {
                Row row = sheet.getRow(rowIndex);
                if (row == null) {
                    continue;
                }

                String planName = formatter.formatCellValue(row.getCell(0));
                String planDateString = formatter.formatCellValue(row.getCell(1));

                if (planName == null || planName.trim().isEmpty() || planDateString == null || planDateString.trim().isEmpty()) {
                    throw new IllegalArgumentException("计划名称和日期不能为空");
                }

                if (bo == null || !bo.getPlanName().equals(planName)) {
                    if (bo != null) {
                        planList.add(bo);
                    }
                    bo = new TbRepairplanBo();
                    bo.setPlanName(planName);

                    try {
                        Date planDate = dateFormat.parse(planDateString);
                        bo.setPlanDate(planDate);
                    } catch (ParseException e) {
                        throw new IllegalArgumentException("无效的日期格式：" + planDateString);
                    }
                    Long planCode = GuidUtil.getZcbhid();
                    bo.setPlanCode(planCode.toString());
                    bo.setStatus("预计划");
                    bo.setRepairplanlistVos(new ArrayList<>());
                }

                TbRepairplanlistBo listBo = new TbRepairplanlistBo();
                // ... 其他字段的设置

                listBo.setLmtType(formatter.formatCellValue(row.getCell(2)));
                listBo.setLmtNumber(formatter.formatCellValue(row.getCell(3)));
                listBo.setWorkerTeam(formatter.formatCellValue(row.getCell(4)));
                listBo.setRepairType(formatter.formatCellValue(row.getCell(5)));
                listBo.setWorkGroup(formatter.formatCellValue(row.getCell(6)));

                String expirationDateString = formatter.formatCellValue(row.getCell(7));
                try {
                    Date expirationDate = dateFormat.parse(expirationDateString);
                    listBo.setExpirationDate(expirationDate);
                } catch (ParseException e) {
                    throw new IllegalArgumentException("无效的日期格式：" + expirationDateString, e);
                }

                listBo.setRepairStartDate(formatter.formatCellValue(row.getCell(8)));
                listBo.setRepairEndDate(formatter.formatCellValue(row.getCell(9)));
                listBo.setStatus(formatter.formatCellValue(row.getCell(10)));

                // 进行数值类型的校验和转换
                String isReplaceDgzz = formatter.formatCellValue(row.getCell(11));
                String isReplaceFdj = formatter.formatCellValue(row.getCell(12));
                if (!isReplaceDgzz.matches("[01]") || !isReplaceFdj.matches("[01]")) {
                    throw new IllegalArgumentException("单元格应该为0或1");
                }
                listBo.setIsReplaceDgzz(Integer.parseInt(isReplaceDgzz));
                listBo.setIsReplaceFdj(Integer.parseInt(isReplaceFdj));

                listBo.setRemark(formatter.formatCellValue(row.getCell(13)));

                bo.getRepairplanlistVos().add(listBo);
            }

            if (bo != null) {
                planList.add(bo);
            }

            for (TbRepairplanBo planBo : planList) {
                iTbRepairplanService.insertPlanAndListByBo(planBo);
            }

        } catch (Exception e) {
            throw new ExecutionException("批量添加操作失败");
        }
        return map;
    }

    @Override
    public Map<String, Object> updateExcel(MultipartFile file) throws Exception {
        Map<String, Object> map = new HashMap<>();
        TbRepairplanBo bo = new TbRepairplanBo();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date earliestStartDate = null;
        Date latestEndDate = null;
        try {

            //只支持xlsx格式
            //Workbook workbook = new HSSFWorkbook(file.getInputStream());
            //只支持xls格式
            //Workbook workbook = new HSSFWorkbook(file.getInputStream());
            Sheet sheet = ExcelUtils.getSheet(file.getInputStream(), file.getOriginalFilename(), 0);
            //Sheet sheet = workbook.getSheetAt(0); // 假设计划在第一个sheet
            // 获取当前时间
            Date now = new Date();

            // 从C1单元格获取检修计划名称
            Row row = sheet.getRow(0);
            if (row != null) {
                Cell cell = row.getCell(2);

                if (cell != null && cell.getCellType() != CellType.BLANK) {
                    bo.setPlanName(cell.getStringCellValue());
                }
            }
            // 设置其他属性
            bo.setPlanCode(GuidUtil.getZcbhid().toString());
            bo.setStatus("预计划");
            List<TbRepairplanlistBo> repairplanlistVos = new ArrayList<>();

            // 从第五行开始读取计划明细
            int emptyRowCounter = 0; // 用于计数连续空行
            for (int i = 4; i <= sheet.getLastRowNum(); i++) {
                row = sheet.getRow(i);
                if (row == null || row.getCell(2) == null || row.getCell(2).getCellType() == CellType.BLANK) {
                    emptyRowCounter++;
                    if (emptyRowCounter > 3) {
                        // 如果连续超过3个空行，则认为后续没有数据
                        break;
                    }
                    continue; // 跳过当前行
                }
                emptyRowCounter = 0; // 重置连续空行计数器

                TbRepairplanlistBo vo = new TbRepairplanlistBo();
                // 从这里开始，我们将为vo设置更多属性
                String lmtNumber = getCellStringValue(row.getCell(2));
                vo.setLmtNumber(lmtNumber);
                //根据车号查询车辆信息设置内容
                TbLocomotiveVo LocVo = tbLocomotiveMapper.selectLocomotive(lmtNumber);
                //修别
                String repairType = getCellStringValue(row.getCell(4));
                if (LocVo != null) {
                    if (LocVo.getWorkGroup() != null) {
                        vo.setWorkGroup(LocVo.getWorkGroup());
                    }
                    if (LocVo.getWorkGroupId() != null) {
                        vo.setWorkGroupId(LocVo.getWorkGroupId());
                    }
                    if (LocVo.getWorkteamname() != null) {
                        vo.setWorkerTeam(LocVo.getWorkteamname());
                    }
                    if (LocVo.getLastRepairChar() != null) {
                        vo.setRepairChar(LocVo.getLastRepairChar());
                    }
                } else {
                    vo.setWorkGroup(getCellStringValue(row.getCell(1)));
                    // vo.setWorkGroupId(LocVo.getWorkGroupId());
                    vo.setWorkerTeam(getCellStringValue(row.getCell(0)));
                    vo.setRepairChar(repairType);
                }
                //车型
                vo.setLmtType(getCellStringValue(row.getCell(3)));

                if ("定期".equals(repairType)) {
                    vo.setRepairType("二级修");
                } else if ("年修".equals(repairType)) {
                    vo.setRepairType("三级修");
                } else if ("整备".equals(repairType)) {
                    vo.setRepairType("二级修");
                } else if ("二级修".equals(repairType)) {
                    vo.setRepairType("二级修");
                } else if ("三级修".equals(repairType)) {
                    vo.setRepairType("三级修");
                } else if ("四级修".equals(repairType)) {
                    vo.setRepairType("四级修");
                } else {
                    // 对于不是"定期"、"年修"、"整备"的所有情况，也设置为"定检"
                    vo.setRepairType("二级修");
                }

                // 修程天数
                vo.setRepairDays(getCellStringValue(row.getCell(5)));
                //备注
                String remark = getCellStringValue(row.getCell(7));
                if (remark != null && remark.contains("架修")) {
                    vo.setRepairType("四级修");
                }
                //vo.setRemark(getCellStringValue(row.getCell(6)));
                String LmtLength = getCellStringValue(row.getCell(8));
                Date startDate = row.getCell(9).getDateCellValue();
                Date endDate = row.getCell(10).getDateCellValue();


                //更改格式
                String startDateStr = startDate != null ? dateFormat.format(startDate) : null;
                String endDateStr = endDate != null ? dateFormat.format(endDate) : null;
                if (startDateStr != null) {
                    vo.setRepairStartDate(startDateStr);
                    //设置有效期
                    // 使用Calendar设置startDate
                    Calendar calendar = Calendar.getInstance();
                    calendar.setTime(startDate);

                    // 在当前日期上加6个月
                    calendar.add(Calendar.MONTH, 6);

                    // 获取新的日期，即有效期时间
                    Date expirationDate = calendar.getTime();
                    vo.setExpirationDate(expirationDate);
                    if (earliestStartDate == null || startDate.before(earliestStartDate)) {
                        earliestStartDate = startDate;
                    }
                }
                if (endDateStr != null) {
                    vo.setRepairEndDate(endDateStr);
                    if (latestEndDate == null || endDate.after(latestEndDate)) {
                        latestEndDate = endDate;
                    }
                }
                // 读取制动系统和探伤有效期
//                Date zdfRepairDate = row.getCell(12).getDateCellValue();
//                Date tsRepairDate = row.getCell(13).getDateCellValue();
                Date zdfRepairDate = null;
                Date tsRepairDate = null;
                Cell zdfCell = row.getCell(12);
                Cell tsCell = row.getCell(13);

// 检查单元格是否为公式类型，并且公式计算结果为日期类型
                if (zdfCell != null && zdfCell.getCellType() == CellType.FORMULA) {
                    if (zdfCell.getCachedFormulaResultType() == CellType.NUMERIC) {
                        if (DateUtil.isCellDateFormatted(zdfCell)) {
                            zdfRepairDate = zdfCell.getDateCellValue();
                        }
                    }
                } else if (zdfCell != null && zdfCell.getCellType() == CellType.NUMERIC) {
                    if (DateUtil.isCellDateFormatted(zdfCell)) {
                        zdfRepairDate = zdfCell.getDateCellValue();
                    }
                }

                if (tsCell != null && tsCell.getCellType() == CellType.FORMULA) {
                    if (tsCell.getCachedFormulaResultType() == CellType.NUMERIC) {
                        if (DateUtil.isCellDateFormatted(tsCell)) {
                            tsRepairDate = tsCell.getDateCellValue();
                        }
                    }
                } else if (tsCell != null && tsCell.getCellType() == CellType.NUMERIC) {
                    if (DateUtil.isCellDateFormatted(tsCell)) {
                        tsRepairDate = tsCell.getDateCellValue();
                    }
                }

                // 比较zdfRepairDate和当前时间
                if (zdfRepairDate != null) {
                    if (zdfRepairDate.before(now)) {
                        vo.setIsReplaceDgzz(1);
                    } else {
                        vo.setIsReplaceDgzz(0);
                    }
                }
                // 比较tsRepairDate和当前时间
                if (tsRepairDate != null) {
                    if (tsRepairDate.before(now)) {
                        vo.setIsReplaceFdj(1);
                    } else {
                        vo.setIsReplaceFdj(0);
                    }
                }

                //存入状态
                vo.setStatus("预计划");
                repairplanlistVos.add(vo);

            }
            bo.setPlanDate(earliestStartDate);
            bo.setRepairplanlistVos(repairplanlistVos);

            // 调用服务层方法，保存计划
            iTbRepairplanService.insertPlanAndListByBo(bo);


        } catch (Exception e) {
            e.printStackTrace();
            throw new ExecutionException("批量添加操作失败");
        }
        return map;
    }

    private String getCellStringValue(Cell cell) {
        if (cell != null) {
            cell.setCellType(CellType.STRING);
            return cell.getStringCellValue();
        }
        return "";
    }

    private Double getCellNumericValue(Cell cell) {
        if (cell != null && cell.getCellType() == CellType.NUMERIC) {
            return cell.getNumericCellValue();
        }
        return 0.0;
    }


    @Override
    public RepairListCountVo selectTwoList(String repairStartDate, String repairEndDate) {
        RepairListCountVo repairListCountVo = new RepairListCountVo();

        String repairType = "二级修";
        //查询数量并赋值
        repairListCountVo.setOverhaulCount(tbRepairplanlistMapper.selectOverhaulCount(repairType, repairStartDate, repairEndDate));
        repairListCountVo.setPreplannedCount(tbRepairplanlistMapper.selectPreplannedCount(repairType, repairStartDate, repairEndDate));
        repairListCountVo.setFinishedCount(tbRepairplanlistMapper.selectFinishedCount(repairType, repairStartDate, repairEndDate));
        repairListCountVo.setCancelledCount(tbRepairplanlistMapper.selectCancelledCount(repairType, repairStartDate, repairEndDate));
        return repairListCountVo;
    }

    @Override
    public RepairListCountVo selectThreeList(String repairStartDate, String repairEndDate) {
        RepairListCountVo repairListCountVo = new RepairListCountVo();

        String repairType = "三级修";
        //查询数量并赋值
        repairListCountVo.setOverhaulCount(tbRepairplanlistMapper.selectOverhaulCount(repairType, repairStartDate, repairEndDate));
        repairListCountVo.setPreplannedCount(tbRepairplanlistMapper.selectPreplannedCount(repairType, repairStartDate, repairEndDate));
        repairListCountVo.setFinishedCount(tbRepairplanlistMapper.selectFinishedCount(repairType, repairStartDate, repairEndDate));
        repairListCountVo.setCancelledCount(tbRepairplanlistMapper.selectCancelledCount(repairType, repairStartDate, repairEndDate));
        return repairListCountVo;
    }

    @Override
    public RepairListCountVo selectFourList(String repairStartDate, String repairEndDate) {
        RepairListCountVo repairListCountVo = new RepairListCountVo();

        String repairType = "四级修";
        //查询数量并赋值
        repairListCountVo.setOverhaulCount(tbRepairplanlistMapper.selectOverhaulCount(repairType, repairStartDate, repairEndDate));
        repairListCountVo.setPreplannedCount(tbRepairplanlistMapper.selectPreplannedCount(repairType, repairStartDate, repairEndDate));
        repairListCountVo.setFinishedCount(tbRepairplanlistMapper.selectFinishedCount(repairType, repairStartDate, repairEndDate));
        repairListCountVo.setCancelledCount(tbRepairplanlistMapper.selectCancelledCount(repairType, repairStartDate, repairEndDate));
        return repairListCountVo;
    }


    public class ExecutionException extends RuntimeException {
        public ExecutionException(String message) {
            super(message);
        }
    }

    // 自定义的数据导入异常类
    public static class DataImportException extends Exception {
        public DataImportException(String message) {
            super(message);
        }
    }

    @Override
    public List<Map<String, Object>> selectTypeList(String repairType, String repairStartDate, String repairEndDate) {
        List<Map<String, Object>> result = new ArrayList<>();
//        List<Map<String,Object>> nowWork = getNowWork();
        TbRepairplanVo tbRepairplanVo = tbRepairplanMapper.selectNowList();
        Long planId = null;
        if (tbRepairplanVo != null) {
            planId = tbRepairplanVo.getId();
        }
//        for (Map<String, Object> week : nowWork) {
        Map<String, Object> two = new HashMap<>();
        two.put("overhaul", tbRepairplanlistMapper.selectDailyOverhaulCount1(planId, "二级修", null/*(LocalDate)week.get("val")*/));
        two.put("preplanned", tbRepairplanlistMapper.selectDailyPreplannedCount1(planId, "二级修", null/*(LocalDate)week.get("val")*/));
        two.put("finished", tbRepairplanlistMapper.selectDailyFinishedCount1(planId, "二级修", null/*(LocalDate)week.get("val")*/));
        two.put("cancelled", tbRepairplanlistMapper.selectDailyCancelledCount1(planId, "二级修", null/*(LocalDate)week.get("val")*/));
        two.put("key", "二级修");
//        }
        result.add(two);
        Map<String, Object> three = new HashMap<>();
        three.put("overhaul", tbRepairplanlistMapper.selectDailyOverhaulCount1(planId, "三级修", null/*(LocalDate)week.get("val")*/));
        three.put("preplanned", tbRepairplanlistMapper.selectDailyPreplannedCount1(planId, "三级修", null/*(LocalDate)week.get("val")*/));
        three.put("finished", tbRepairplanlistMapper.selectDailyFinishedCount1(planId, "三级修", null/*(LocalDate)week.get("val")*/));
        three.put("cancelled", tbRepairplanlistMapper.selectDailyCancelledCount1(planId, "三级修", null/*(LocalDate)week.get("val")*/));
        three.put("key", "三级修");
        result.add(three);

        Map<String, Object> four = new HashMap<>();
        four.put("overhaul", tbRepairplanlistMapper.selectDailyOverhaulCount1(planId, "四级修", null/*(LocalDate)week.get("val")*/));
        four.put("preplanned", tbRepairplanlistMapper.selectDailyPreplannedCount1(planId, "四级修", null/*(LocalDate)week.get("val")*/));
        four.put("finished", tbRepairplanlistMapper.selectDailyFinishedCount1(planId, "四级修", null/*(LocalDate)week.get("val")*/));
        four.put("cancelled", tbRepairplanlistMapper.selectDailyCancelledCount1(planId, "四级修", null/*(LocalDate)week.get("val")*/));
        four.put("key", "四级修");
        result.add(four);
        return result;
    }

    @Override
    public LocNumberVo selectLmtRepair(String startDate, String endDate) {
        LocNumberVo locNumberVo = new LocNumberVo();

        TbRepairplanVo tbRepairplanVo = tbRepairplanMapper.selectNowList();
        Long planId = tbRepairplanVo.getId();
        //获得数量
        int overhaulCount = tbRepairplanlistMapper.selectLmtOverhaulCount(planId, startDate, endDate);
        int allCount = tbRepairplanlistMapper.selectLmtAllCount(planId, startDate, endDate);

        locNumberVo.setOverhaulCount(overhaulCount);
        locNumberVo.setAllCount(allCount);

        // 确保分母不为零
        if (allCount > 0) {
            double rate = (double) overhaulCount / allCount * 100;
            int rateCount = (int) Math.ceil(rate); // 向上取整
            locNumberVo.setRateCount(rateCount);
        } else {
            locNumberVo.setRateCount(0); // 如果allCount为0，则设置rateCount为0以避免除以0
        }

        return locNumberVo;
    }

    @Override
    public boolean isTwoTypeById(Long id) {
        return tbRepairplanlistMapper.isTwoTypeById(id);
    }

    @Override
    public TableDataInfo<TbRepairplanlistVo> selectLocomotiveList1(String lmtType, String lmtNumber, String workerTeam, String planCode, String planName, String repairChar, String repairStartDate, String repairEndDate, String status, PageQuery pageQuery) {
        List<TbRepairplanlistVo> result = tbRepairplanlistMapper.selectLocomotiveList1(lmtType, lmtNumber, workerTeam, planCode, planName, repairChar, repairStartDate, repairEndDate, status);

        if (pageQuery.getPageSize() != null && pageQuery.getPageNum() != null) {
            List<TbRepairplanlistVo> page = ListUtil.page(pageQuery.getPageNum() - 1, pageQuery.getPageSize(), result);
            TableDataInfo res = new TableDataInfo<>(page, result.size());
            return res;
        } else {
            return TableDataInfo.build(result);
        }
    }

    @Override
    public Map<String, Object> selectTypeList1() {
        List<Map<String, Object>> nowWork = getNowWork();
        Map<String, Object> result = new HashMap<>();
        TbRepairplanVo tbRepairplanVo = tbRepairplanMapper.selectNowList();
        Long planId = tbRepairplanVo.getId();
        int preplanned = tbRepairplanlistMapper.selectDailyPreplannedCountToWeek1(planId);
        int finished = tbRepairplanlistMapper.selectDailyFinishedCountToWeek1(planId, null);
        int finished2 = tbRepairplanlistMapper.selectDailyFinishedCountToWeek2(planId, null);
        result.put("preplanned", preplanned);
        result.put("finished", finished);
        DecimalFormat decimalFormat = new DecimalFormat("#.0");

        if (preplanned != 0 && finished2 != 0) {
            result.put("finishedToPreplanned", decimalFormat.format(((double) finished2 / (double) preplanned) * 100));
        } else {
            result.put("finishedToPreplanned", "0");
        }
        return result;
    }

    /**
     * 根据车型车号去查询id
     *
     * @param lmtType
     * @param lmtNumber
     * @return
     */
    @Override
    public List<Long> selectIdsByType(String lmtType, String repairType) {
        return baseMapper.selectIdsByType(lmtType, repairType);
    }

    @Override
    public Map<String, Object> getStats() {
        Map<String, Object> result = new HashMap<>();
        result.put("locomotiveCount", tbLocomotiveMapper.selectAllCount());
        result.put("lmtTypeCount", tbLmttypeMapper.selectAllCount());
        TbRepairplanVo tbRepairplanVo = tbRepairplanMapper.selectNowList();
        Long planId = tbRepairplanVo.getId();
        int planCount = tbRepairplanlistMapper.selectLmtNumberCount(planId);
        //计划检修数
        result.put("planCount", planCount);
        //实际检修数 (有问题)
        result.put("actualCount", tbRepairplanlistMapper.selectActualCount(planId));
        //完成数
        Integer finishCount = tbRepairplanlistMapper.selectLmtFinish(planId);
        result.put("finishCount", finishCount);
        //完成率
        DecimalFormat decimalFormat = new DecimalFormat("#.0");
        if (planCount != 0 && finishCount != 0) {
            result.put("finishedToPlan", decimalFormat.format(((double) finishCount / (double) planCount) * 100));
        } else {
            result.put("finishedToPlan", "0");
        }
        //检修中数值
        result.put("repairCount", tbRepairplanlistMapper.selectRepairCount(planId));
        //待检修数值
        result.put("toRepairCount", tbRepairplanlistMapper.selectToRepairCount(planId));
        return result;
    }

    @Override
    public ResponseEntity<byte[]> createWord(TbRepairplanlistVo tbRepairplanlistVo, List<TbLmtrepairWorkdetailVo> list) {
        try {
            XWPFDocument document = new XWPFDocument();
            //字体靠右显示 第一段
            XWPFParagraph paragraph1 = document.createParagraph();
            paragraph1.setAlignment(ParagraphAlignment.RIGHT); // 设置段落右对齐
            XWPFRun run1 = paragraph1.createRun();
            run1.setText(tbRepairplanlistVo.getLmtType() + "-" + (tbRepairplanlistVo.getStartTime() == null ? DateUtils.getYear(new Date()) : DateUtils.getYear(tbRepairplanlistVo.getStartTime())));
            run1.setFontSize(16);
            // 附件位置
            XWPFParagraph paragraph2 = document.createParagraph();
            XWPFRun run2 = paragraph2.createRun();
            run2.setText("大型养路机械" + tbRepairplanlistVo.getRepairType() + "记录");
            run2.setFontSize(16);
            //加两行空
            for (int i = 0; i < 2; i++) {
                XWPFParagraph emptyParagraph = document.createParagraph();
                XWPFRun emptyRun = emptyParagraph.createRun();
                emptyRun.addBreak(BreakType.TEXT_WRAPPING);
            }
            //标题
            XWPFParagraph paragraph3 = document.createParagraph();
            paragraph3.setAlignment(ParagraphAlignment.CENTER); // 设置段落居中对齐
            XWPFRun run3 = paragraph3.createRun();
            run3.setText("大型养路机械" + tbRepairplanlistVo.getRepairType() + "记录");
            run3.setFontSize(32);
            run3.setBold(true);
            //加一行空
            for (int i = 0; i < 1; i++) {
                XWPFParagraph emptyParagraph = document.createParagraph();
                XWPFRun emptyRun = emptyParagraph.createRun();
                emptyRun.addBreak(BreakType.TEXT_WRAPPING);
            }
            XWPFParagraph paragraph4 = document.createParagraph();
            paragraph4.setAlignment(ParagraphAlignment.CENTER); // 设置段落居中对齐
            XWPFRun run4 = paragraph4.createRun();
            run4.setText("编号：___________");
            run4.setFontSize(16);
            run4.setBold(true);

            //加十行空
            for (int i = 0; i < 11; i++) {
                XWPFParagraph emptyParagraph = document.createParagraph();
                XWPFRun emptyRun = emptyParagraph.createRun();
                emptyRun.addBreak(BreakType.TEXT_WRAPPING);
            }

            XWPFParagraph paragraph5 = document.createParagraph();
            XWPFParagraph paragraph6 = document.createParagraph();
            XWPFParagraph paragraph7 = document.createParagraph();
            XWPFRun run5 = paragraph5.createRun();
            XWPFRun run6 = paragraph6.createRun();
            XWPFRun run7 = paragraph7.createRun();
            run5.setText("                                  机械名称：" + tbRepairplanlistVo.getLmtType());
            run6.setText("                                  机械型号：" + tbRepairplanlistVo.getLmtType());
            run7.setText("                                  机械编号：" + tbRepairplanlistVo.getLmtNumber());
            run5.setFontSize(16);
            run5.setBold(true);
            run6.setFontSize(16);
            run6.setBold(true);
            run7.setFontSize(16);
            run7.setBold(true);

            XWPFParagraph paragraph8 = document.createParagraph();
            paragraph8.setAlignment(ParagraphAlignment.CENTER); // 设置段落居中对齐
            XWPFRun run8 = paragraph8.createRun();
            run8.setText("___________段");
            run8.setFontSize(16);
            run8.setBold(true);

            XWPFParagraph paragraph9 = document.createParagraph();
            XWPFRun run9 = paragraph9.createRun();
            run9.setText(tbRepairplanlistVo.getLmtType() + "-" +( tbRepairplanlistVo.getStartTime() == null ? DateUtils.getYear(new Date()) : DateUtils.getYear(tbRepairplanlistVo.getStartTime())));
            run9.setFontSize(16);
            run9.setBold(true);
            XWPFParagraph paragraph10 = document.createParagraph();
            XWPFRun run10 = paragraph10.createRun();
            run10.setText("总成部件：                         修程类别：" + tbRepairplanlistVo.getRepairType() + "              检修部门：" + tbRepairplanlistVo.getWorkGroup());
            run10.setFontSize(13);

            // 添加表格
            XWPFTable table = document.createTable(list.size() + 1, 8);
            XWPFTableRow row1 = table.getRow(0);
            CTTblWidth cellWidth0 = CTTblWidth.Factory.newInstance();
            cellWidth0.setW(BigInteger.valueOf(500));
            row1.getCell(0).setText("序号");
            row1.getCell(0).getCTTc().addNewTcPr().addNewTcW().set(cellWidth0);

            CTTblWidth cellWidth1 = CTTblWidth.Factory.newInstance();
            cellWidth1.setW(BigInteger.valueOf(1200));
            row1.getCell(1).setText("检修项目");
            row1.getCell(1).getCTTc().addNewTcPr().addNewTcW().set(cellWidth1);
            row1.getCell(2).setText("检修内容");
            row1.getCell(2).getCTTc().addNewTcPr().addNewTcW().set(cellWidth1);

            row1.getCell(3).setText("检修情况");
            row1.getCell(3).getCTTc().addNewTcPr().addNewTcW().set(cellWidth1);

            row1.getCell(4).setText("检修人");
            row1.getCell(4).getCTTc().addNewTcPr().addNewTcW().set(cellWidth1);

            row1.getCell(5).setText("检修日期");
            row1.getCell(5).getCTTc().addNewTcPr().addNewTcW().set(cellWidth1);

            row1.getCell(6).setText("检验人");
            row1.getCell(6).getCTTc().addNewTcPr().addNewTcW().set(cellWidth1);

            row1.getCell(7).setText("检验日期");
            row1.getCell(7).getCTTc().addNewTcPr().addNewTcW().set(cellWidth1);

            row1.setHeight(500);


            row1.getCell(0).setVerticalAlignment(XWPFTableCell.XWPFVertAlign.CENTER); // 设置垂直居中对齐
            row1.getCell(1).setVerticalAlignment(XWPFTableCell.XWPFVertAlign.CENTER); // 设置垂直居中对齐
            row1.getCell(2).setVerticalAlignment(XWPFTableCell.XWPFVertAlign.CENTER); // 设置垂直居中对齐
            row1.getCell(3).setVerticalAlignment(XWPFTableCell.XWPFVertAlign.CENTER); // 设置垂直居中对齐
            row1.getCell(4).setVerticalAlignment(XWPFTableCell.XWPFVertAlign.CENTER); // 设置垂直居中对齐
            row1.getCell(5).setVerticalAlignment(XWPFTableCell.XWPFVertAlign.CENTER); // 设置垂直居中对齐
            row1.getCell(6).setVerticalAlignment(XWPFTableCell.XWPFVertAlign.CENTER); // 设置垂直居中对齐
            row1.getCell(7).setVerticalAlignment(XWPFTableCell.XWPFVertAlign.CENTER); // 设置垂直居中对齐
            row1.getCell(0).getParagraphs().get(0).setAlignment(ParagraphAlignment.CENTER);//左右居中
            row1.getCell(1).getParagraphs().get(0).setAlignment(ParagraphAlignment.CENTER);//左右居中
            row1.getCell(2).getParagraphs().get(0).setAlignment(ParagraphAlignment.CENTER);//左右居中
            row1.getCell(3).getParagraphs().get(0).setAlignment(ParagraphAlignment.CENTER);//左右居中
            row1.getCell(4).getParagraphs().get(0).setAlignment(ParagraphAlignment.CENTER);//左右居中
            row1.getCell(5).getParagraphs().get(0).setAlignment(ParagraphAlignment.CENTER);//左右居中
            row1.getCell(6).getParagraphs().get(0).setAlignment(ParagraphAlignment.CENTER);//左右居中
            row1.getCell(7).getParagraphs().get(0).setAlignment(ParagraphAlignment.CENTER);//左右居中
            System.out.println(list.size());
            for (int i = 1; i < (list.size() + 1); i++) {
                System.out.println(i);
                TbLmtrepairWorkdetailVo tbLmtrepairWorkdetailVo = list.get(i-1);
                XWPFTableRow row = table.getRow(i);
                if (tbLmtrepairWorkdetailVo==null){
                    row.getCell(0).getCTTc().addNewTcPr().addNewTcW().set(cellWidth0);
                    row.getCell(1).getCTTc().addNewTcPr().addNewTcW().set(cellWidth1);
                    row.getCell(2).getCTTc().addNewTcPr().addNewTcW().set(cellWidth1);
                    row.getCell(3).getCTTc().addNewTcPr().addNewTcW().set(cellWidth1);
                    row.getCell(4).getCTTc().addNewTcPr().addNewTcW().set(cellWidth1);
                    row.getCell(5).getCTTc().addNewTcPr().addNewTcW().set(cellWidth1);
                    row.getCell(6).getCTTc().addNewTcPr().addNewTcW().set(cellWidth1);
                    row.getCell(7).getCTTc().addNewTcPr().addNewTcW().set(cellWidth1);
                    continue;
                }
                row.getCell(0).setText(i + "");
                row.getCell(0).getCTTc().addNewTcPr().addNewTcW().set(cellWidth0);

                row.getCell(1).setText(tbLmtrepairWorkdetailVo.getWorkKind());
                row.getCell(1).getCTTc().addNewTcPr().addNewTcW().set(cellWidth1);
                row.getCell(2).setText(tbLmtrepairWorkdetailVo.getWorkCategory());
                row.getCell(2).getCTTc().addNewTcPr().addNewTcW().set(cellWidth1);
                row.getCell(3).setText(tbLmtrepairWorkdetailVo.getStatus());
                row.getCell(3).getCTTc().addNewTcPr().addNewTcW().set(cellWidth1);
                row.getCell(4).setText(StringUtils.isNotBlank(tbLmtrepairWorkdetailVo.getWorkUserName())?tbLmtrepairWorkdetailVo.getWorkUserName():tbLmtrepairWorkdetailVo.getWorkUser());
                row.getCell(4).getCTTc().addNewTcPr().addNewTcW().set(cellWidth1);
                row.getCell(5).setText(tbLmtrepairWorkdetailVo.getEndTime() == null ? "" : DateUtils.dateTime(tbLmtrepairWorkdetailVo.getEndTime()));
                row.getCell(5).getCTTc().addNewTcPr().addNewTcW().set(cellWidth1);
                row.getCell(6).setText(StringUtils.isNotBlank(tbLmtrepairWorkdetailVo.getCheckUserName())?tbLmtrepairWorkdetailVo.getCheckUserName():tbLmtrepairWorkdetailVo.getCheckUser());
                row.getCell(6).getCTTc().addNewTcPr().addNewTcW().set(cellWidth1);
                row.getCell(7).setText(tbLmtrepairWorkdetailVo.getCheckTime() == null ? "" : DateUtils.dateTime(tbLmtrepairWorkdetailVo.getCheckTime()));
                row.getCell(7).getCTTc().addNewTcPr().addNewTcW().set(cellWidth1);
                row.setHeight(500);

                row.getCell(0).setVerticalAlignment(XWPFTableCell.XWPFVertAlign.CENTER); // 设置垂直居中对齐
                row.getCell(1).setVerticalAlignment(XWPFTableCell.XWPFVertAlign.CENTER); // 设置垂直居中对齐
                row.getCell(2).setVerticalAlignment(XWPFTableCell.XWPFVertAlign.CENTER); // 设置垂直居中对齐
                row.getCell(3).setVerticalAlignment(XWPFTableCell.XWPFVertAlign.CENTER); // 设置垂直居中对齐
                row.getCell(4).setVerticalAlignment(XWPFTableCell.XWPFVertAlign.CENTER); // 设置垂直居中对齐
                row.getCell(5).setVerticalAlignment(XWPFTableCell.XWPFVertAlign.CENTER); // 设置垂直居中对齐
                row.getCell(6).setVerticalAlignment(XWPFTableCell.XWPFVertAlign.CENTER); // 设置垂直居中对齐
                row.getCell(7).setVerticalAlignment(XWPFTableCell.XWPFVertAlign.CENTER); // 设置垂直居中对齐

                row.getCell(0).getParagraphs().get(0).setAlignment(ParagraphAlignment.CENTER);
                row.getCell(1).getParagraphs().get(0).setAlignment(ParagraphAlignment.CENTER);
                row.getCell(2).getParagraphs().get(0).setAlignment(ParagraphAlignment.CENTER);
                row.getCell(3).getParagraphs().get(0).setAlignment(ParagraphAlignment.CENTER);
                row.getCell(4).getParagraphs().get(0).setAlignment(ParagraphAlignment.CENTER);
                row.getCell(5).getParagraphs().get(0).setAlignment(ParagraphAlignment.CENTER);
                row.getCell(6).getParagraphs().get(0).setAlignment(ParagraphAlignment.CENTER);
                row.getCell(7).getParagraphs().get(0).setAlignment(ParagraphAlignment.CENTER);
            }


            ByteArrayOutputStream out = new ByteArrayOutputStream();
            document.write(out);

            HttpHeaders headers = new HttpHeaders();
            headers.add("Content-Disposition", "attachment; filename=" +
                URLEncoder.encode(tbRepairplanlistVo.getLmtNumber() + "-" + tbRepairplanlistVo.getRepairType() + "检修记录.doc", "UTF-8"));
            headers.add("Content-Type", "application/vnd.openxmlformats-officedocument.wordprocessingml.document");


            return ResponseEntity.ok()
                .headers(headers)
                .contentLength(out.size())
                .body(out.toByteArray());

        } catch (IOException e) {
            e.printStackTrace();
            return ResponseEntity.badRequest().build();
        }
    }


    public List<Map<String, Object>> getNowWork() {
        LocalDate currentDate = LocalDate.now();
        LocalDate firstDayOfWeek = currentDate.with(DayOfWeek.MONDAY);
        // 获取本周的最后一天
        LocalDate lastDayOfWeek = firstDayOfWeek.plusDays(6);
        // 获取本周的所有日期
        List<LocalDate> datesOfWeek = new ArrayList<>();
        for (LocalDate date = firstDayOfWeek; !date.isAfter(lastDayOfWeek); date = date.plusDays(1)) {
            datesOfWeek.add(date);

        }
        String[] names = new String[]{"周一", "周二", "周三", "周四", "周五", "周六", "周日"};
        List<Map<String, Object>> all = new ArrayList<>();
        for (int i = 0; i < names.length; i++) {
            Map<String, Object> ps = new HashMap<>();
            ps.put("key", names[i]);
            ps.put("val", datesOfWeek.get(i));
            all.add(ps);
        }
        return all;
    }
}
